<template>
	<cl-crud ref="Crud">
		<cl-row>
			<!-- 刷新按钮 -->
			<cl-refresh-btn />
			<!-- 新增按钮 -->
			<cl-add-btn />
			<!-- 删除按钮 -->
			<!-- <cl-multi-delete-btn /> -->
			<cl-export-btn :columns="Table?.columns" />
			<cl-flex1 />
			<!-- 条件搜索 -->
			<cl-search ref="Search" />
		</cl-row>

		<cl-row>
			<!-- 数据表格 -->
			<cl-table ref="Table">
				<!-- 插槽的渲染方式 #[component.name] -->
				<template #slot-appoint-btn="{ scope }">
					<el-button
						type="success"
						@click="
							() => {
								showAppointDialog(scope.row.id);
							}
						"
						>预约</el-button
					>
				</template>
				<template #slot-change-btn="{ scope }">
					<el-button
						type="success"
						@click="
							() => {
								showAppointDialog(scope.row.id);
							}
						"
						>改约</el-button
					>
				</template>
				<template #slot-edit-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								editStudent(scope.row.id);
							}
						"
						>学员信息</el-button
					>
				</template>
				<template #slot-profile-btn="{ scope }">
					<el-button
						type="primary"
						@click="
							() => {
								profileStudent(scope.row);
							}
						"
						>编辑档案</el-button
					>
				</template>
			</cl-table>
		</cl-row>

		<cl-row>
			<cl-flex1 />
			<!-- 分页控件 -->
			<cl-pagination />
		</cl-row>

		<!-- 新增、编辑 -->
		<cl-upsert ref="upsertRef" />
	</cl-crud>
	<!--档案编辑弹窗-->
	<profile-dialog
		v-model="profileDialog.visible"
		:student-id="profileDialog.studentId"
		:student-info="profileDialog.studentInfo"
		@saved="refresh"
	/>
	<!-- 学员信息编辑弹窗 -->
	<student-edit-dialog
		v-model="studentDialog.visible"
		:student-id="studentDialog.studentId"
		@success="refresh"
	/>
	<!--预约弹窗-->
	<week-appoint-dialog
		v-model="appointDialogVisible"
		:student-id="currentStudentId"
		@success="refresh"
	/>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'student-student'
});

import { useCrud, useTable, useUpsert, useSearch } from '@cool-vue/crud';
import { useCool } from '/@/cool';
import { useI18n } from 'vue-i18n';
import { reactive, ref, watch, nextTick } from 'vue';
import { useDict } from '/$/dict';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import { useBase } from '/$/base';
import ProfileDialog from '../../appointment/components/ProfileDialog.vue';
import StudentEditDialog from '../components/ShopStudentEdit.vue';
import WeekAppointDialog from '../components/WeekAppointDialog.vue';

const { service, setRefs, refs } = useCool();
const { t } = useI18n();
const route = useRoute();
const { user } = useBase();
const appointDialogVisible = ref(false);
const currentStudentId = ref(0);

// 选项
const options = reactive({
	gender: [
		{ label: t('男'), value: 0 },
		{ label: t('女'), value: 1 }
		// { label: t('未知'), value: 2 }
	],
	salesList: [],
	train: [
		{ label: t('全部'), value: '' },
		{ label: t('有训练'), value: 1 },
		{ label: t('无训练'), value: 2 }
	]
});
const { dict } = useDict();
const disabled = ref(true);
// 档案信息弹窗数据
const profileDialog = reactive({
	visible: false,
	studentId: 0,
	studentInfo: {}
});

function profileStudent(row: any) {
	profileDialog.studentId = row.id;
	profileDialog.studentInfo = row;
	profileDialog.studentInfo.userBirthday = row.birthday;
	profileDialog.studentInfo.userName = row.name;
	profileDialog.studentInfo.userPhone = row.phone;
	profileDialog.studentInfo.userGender = row.gender;
	profileDialog.visible = true;
}

// 学员信息弹窗数据
const studentDialog = reactive({
	visible: false,
	studentId: 0
});

// 编辑学员信息
function editStudent(id: number) {
	studentDialog.studentId = id;
	studentDialog.visible = true;
}
// 添加 upsertRef
// const upsertRef = ref();
// cl-upsert
const upsertRef = useUpsert({
	items: [
		{
			label: t('会员卡号'),
			prop: 'studentNo',
			component: {
				name: 'el-input',
				props: {
					clearable: true,
					placeholder: '新增时自动生成',
					disabled
				}
			},
			required: true
		},
		{
			label: t('姓名'),
			prop: 'name',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('手机号'),
			prop: 'phone',
			component: { name: 'el-input', props: { clearable: true } },
			span: 12,
			required: true
		},
		{
			label: t('性别'),
			prop: 'gender',
			component: { name: 'el-radio-group', options: options.gender },
			value: '',
			span: 8,
			required: true
		},
		{
			label: t('生日'),
			prop: 'birthday',
			component: {
				name: 'el-date-picker',
				props: { type: 'date', valueFormat: 'YYYY-MM-DD' }
			},
			span: 8,
			required: true
		},

		{
			label: t('微信昵称'),
			prop: 'wechatNickName',
			component: { name: 'el-input', props: { clearable: true } },
			span: 8
		},
		{
			label: t('左眼度数'),
			prop: 'leftEye',
			hook: 'number',
			component: { name: 'el-input-number', props: {} },
			span: 8
		},
		{
			label: t('右眼度数'),
			prop: 'rightEye',
			hook: 'number',
			component: { name: 'el-input-number', props: {} },
			span: 8
		},
		{
			label: t('项目'),
			prop: 'project',
			component: {
				name: 'cl-select',
				props: {
					tree: true,
					checkStrictly: true,
					options: dict.get('Project')
				}
			},
			span: 8
		},
		{
			label: t('来源'),
			prop: 'source',
			component: {
				name: 'el-select',
				options: dict.get('Source')
			},
			span: 8
		},
		{
			label: t('所属门店'),
			prop: 'shop',
			component: {
				name: 'el-select',
				options: dict.get('Shop')
			},
			span: 8
		},
		{
			label: t('销售'),
			prop: 'sales',
			component: { name: 'el-select', options: options.salesList },
			span: 8,
			ref: setRefs('sales'),
			default: user.info?.id
		},
		{
			label: t('跟进状态'),
			prop: 'flowStatus',
			component: {
				name: 'el-select',
				options: dict.get('flowStatus')
			},
			span: 12
		},
		{
			label: t('入组'),
			prop: 'inGroup',
			component: {
				name: 'cl-select',
				tree: true,
				checkStrictly: true,
				options: dict.get('inGroup')
			},
			span: 12
		},
		{
			label: t('备注'),
			prop: 'remark',
			component: {
				name: 'el-input',
				props: { type: 'textarea', rows: 4 }
			}
		}
	],
	onOpen() {
		if (!upsertRef.value.form.studentNo) {
			upsertRef.value.form.studentNo = new Date().getTime().toString().slice(-10);
		}
		service.base.sys.user.getSelectList().then((res: any) => {
			if (res) {
				const salesItem = upsertRef.value.items.find(item => item.prop === 'sales');
				console.log('salesList', res, salesItem);
				salesItem.component.options = res;
			}
		});
	},
	async onSubmit(data, { done, close, next }) {
		next({
			...data,
			sales: data.sales || user.info?.id
		});
	}
});

// cl-table
const Table = useTable({
	columns: [
		// { type: 'selection', hidden: true },

		{ label: t('ID'), prop: 'id', minWidth: 80 },
		{ label: t('预约状态'), prop: 'appointmentText', minWidth: 140 },
		{ label: t('预约门店'), prop: 'appointmentShop', minWidth: 140 },
		{ label: t('最近预约日期'), prop: 'appointmentDate', minWidth: 140 },
		{ label: t('姓名'), prop: 'name', minWidth: 140 },
		{ label: t('手机号'), prop: 'phone', minWidth: 140 },
		{
			label: t('性别'),
			prop: 'gender',
			minWidth: 60,
			formatter: (row, column, cellValue) => {
				const gender = options.gender.find(item => item.value === cellValue);
				return gender ? gender.label : cellValue;
			}
		},
		{
			label: t('生日'),
			prop: 'birthday',
			minWidth: 140,
			sortable: 'custom',
			component: {
				name: 'cl-date-text',
				props: { format: 'YYYY-MM-DD' }
			}
		},
		{
			label: t('来源'),
			prop: 'source',
			formatter: (row, column, cellValue) => {
				const source = dict.get('Source').value.find(item => item.value === cellValue);
				return source ? source.label : cellValue;
			}
		},
		{
			label: t('所属门店'),
			prop: 'shop',
			width: 100,
			formatter: (row, column, cellValue) => {
				const shop = dict.get('Shop').value.find(item => item.value === cellValue);
				return shop ? shop.label : cellValue;
			}
		},
		{ label: t('销售'), prop: 'salesName' },
		{
			label: t('项目'),
			prop: 'project',
			dict: dict.get('Project'),
			minWidth: 200
		},
		{
			label: t('入组'),
			prop: 'inGroup',
			formatter: (row, column, cellValue) => {
				const inGroup = dict.get('inGroup').value.find(item => item.value === cellValue);
				return inGroup ? inGroup.label : cellValue;
			},
			minWidth: 100
		},
		{ label: t('训练次数'), prop: 'trainCount', minWidth: 100 },
		{ label: t('赠送次数'), prop: 'giftCount', minWidth: 100 },
		{ label: t('备注'), prop: 'remark', showOverflowTooltip: true },
		{ label: t('预约状态'), prop: 'appointmentTextShop', minWidth: 80, hidden: true },
		{ label: t('预约门店'), prop: 'appointmentShopShop', minWidth: 120, hidden: true },
		{ label: t('最近预约日期'), prop: 'appointmentDateShop', minWidth: 100, hidden: true },
		{
			type: 'op',
			buttons: ['slot-appoint-btn', 'slot-cancle-btn'],
			width: 400
		}
	]
});

// cl-search
const Search = useSearch({
	items: [
		{
			prop: 'train',
			component: {
				name: 'cl-select',
				props: { options: options.train, placeholder: '训练次数' }
			}
		},
		{
			prop: 'source',
			component: {
				name: 'cl-select',
				props: { options: dict.get('Source'), placeholder: '渠道' }
			}
		},
		{
			prop: 'project',
			component: {
				name: 'cl-select',
				props: {
					tree: true,
					checkStrictly: true,
					options: dict.get('Project'),
					placeholder: '项目'
				}
			}
		},
		{
			prop: 'inGroup',
			component: {
				name: 'cl-select',
				props: { options: dict.get('inGroup'),tree: true,
				checkStrictly: true, placeholder: '入组' }
			}
		},
		{
			prop: 'shopId',
			component: {
				name: 'cl-select',
				props: { options: dict.get('Shop'), placeholder: '门店' }
			}
		},
		{
			prop: 'phone',
			component: {
				name: 'el-input',
				props: { placeholder: '请输入电话' }
			}
		},
		{
			prop: 'name',
			component: {
				name: 'el-input',
				props: { placeholder: '请输入姓名' }
			}
		}
	]
});

// cl-crud
const Crud = useCrud(
	{
		service: service.student.student,
		async onRefresh(params, { next, done, render }) {
			if (route.path.endsWith('myStudent')) {
				params.sales = user.info?.id;
			}
			if (route.path.endsWith('flowStudent')) {
				params.sales = user.info?.id;
				params.appoint = 0;
			}
			if (route.path.endsWith('myAppoint')) {
				params.sales = user.info?.id;
				params.appoint = 1;
			}
			if (route.path.endsWith('seaStudent')) {
				// params.appoint = 0;
				params.flowStatus = [131];
			}
			if (route.path.endsWith('shopStudent')) {
				params.shop = user.info?.shop;
				params.flowStatus = [134, 133];
			}
			params.showAppoint = 1;
			const { list } = await next(params);

			// 渲染数据
			render(list);
		}
	},
	app => {
		app.refresh();
	}
);

watch(
	() => route.path,
	async newPath => {
		// 刷新数据
		await Crud.value?.refresh();
		// 更新表格列配置
		if (Table.value?.columns) {
			// 正在跟进可以预约
			const appointmentTextColumn = Table.value.columns.find(
				col => col.prop === 'appointmentText'
			);
			const appointmentShopColumn = Table.value.columns.find(
				col => col.prop === 'appointmentShop'
			);
			const appointmentDateColumn = Table.value.columns.find(
				col => col.prop === 'appointmentDate'
			);
			const appointmentTextShopColumn = Table.value.columns.find(
				col => col.prop === 'appointmentTextShop'
			);
			const appointmentShopShopColumn = Table.value.columns.find(
				col => col.prop === 'appointmentShopShop'
			);
			const appointmentDateShopColumn = Table.value.columns.find(
				col => col.prop === 'appointmentDateShop'
			);

			const opColumn = Table.value.columns.find(col => col.type === 'op');
			if (newPath.endsWith('flowStudent')) {
				appointmentShopColumn ? (appointmentShopColumn.hidden = true) : '';
				appointmentDateColumn ? (appointmentDateColumn.hidden = true) : '';
				opColumn ? (opColumn.buttons = ['slot-appoint-btn', 'edit']) : '';
			}
			// 已预约，可以取消预约
			else if (newPath.endsWith('myAppoint')) {
				appointmentShopColumn ? (appointmentShopColumn.hidden = false) : '';
				appointmentDateColumn ? (appointmentDateColumn.hidden = false) : '';
				opColumn ? (opColumn.buttons = ['slot-change-btn', 'edit']) : '';
			}
			// 门店学员可以改约
			else if (newPath.endsWith('shopStudent')) {
				appointmentTextColumn ? (appointmentTextColumn.hidden = true) : '';
				appointmentShopColumn ? (appointmentShopColumn.hidden = true) : '';
				appointmentDateColumn ? (appointmentDateColumn.hidden = true) : '';
				appointmentTextShopColumn ? (appointmentTextShopColumn.hidden = false) : '';
				appointmentShopShopColumn ? (appointmentShopShopColumn.hidden = false) : '';
				appointmentDateShopColumn ? (appointmentDateShopColumn.hidden = false) : '';
				opColumn
					? (opColumn.buttons = [
							'slot-change-btn',
							'slot-edit-btn',
							'slot-profile-btn'
						])
					: '';
			} else {
				appointmentShopColumn ? (appointmentShopColumn.hidden = false) : '';
				appointmentDateColumn ? (appointmentDateColumn.hidden = false) : '';
				opColumn ? (opColumn.buttons = ['edit']) : '';
			}
		}
	},
	{ immediate: true }
);

// 刷新
function refresh(params?: any) {
	Crud.value?.refresh(params);
}
function showAppointDialog(studentId) {
	currentStudentId.value = studentId;
	appointDialogVisible.value = true;
}
</script>
<style scoped>
.appoint-item {
	margin-top: 5px;
	margin-bottom: 20px;
}
.timeList {
	margin-top: 20px;
}

.time-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.time-slot {
	width: 45%;
	padding: 10px;
	text-align: center;
	border-radius: 4px;
	cursor: pointer;
	background-color: #fff;
	border: 1px solid #dcdfe6;
}

.time-slot.available {
	background-color: #e1f3d8;
	color: #67c23a;
}

.time-slot.unavailable {
	background-color: #fde2e2;
	color: #f56c6c;
	cursor: not-allowed;
}

.time-slot.selected {
	background-color: #fff;
	border: 1px solid #409eff;
	color: #409eff;
}
</style>
